package drds.data_migrate.util;


import drds.common.Author;
import drds.data_migrate.Authors;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@Author(name = Authors.LI_YANG)
@Slf4j
public final class Jdbcs
{


    //
    public static List<String> getColumnNameList(@NonNull String jdbcUrl, @NonNull String username, @NonNull String password, @NonNull String tableName) throws SQLException
    {
        Connection connection = Jdbc.getConnection(jdbcUrl, username, password);
        return getColumnNameList(connection, tableName);
    }

    public static List<String> getColumnNameList(@NonNull Connection connection, @NonNull String tableName) throws SQLException
    {
        List<String> columnNameList = new ArrayList<String>();
        Statement statement = null;
        ResultSet resultSet = null;
        String sql = null;
        try
        {
            statement = connection.createStatement();
            sql = String.format("select * from %s where 1=2", tableName);
            resultSet = statement.executeQuery(sql);
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            for (int i = 0, columnCount = resultSetMetaData.getColumnCount(); i < columnCount; i++)
            {
                columnNameList.add(resultSetMetaData.getColumnName(i + 1));
            }

        } catch (SQLException e)
        {
            throw e;
        } finally
        {
            Jdbc.close(resultSet, statement, connection);
        }

        return columnNameList;
    }


    public static void sessionSet(Connection connection, List<String> sessionSqlList) throws SQLException
    {
        if (null == sessionSqlList || sessionSqlList.isEmpty())
        {
            return;
        }

        Statement statement = connection.createStatement();

        for (String sessionSql : sessionSqlList)
        {

            Jdbc.execute(statement, sessionSql);
        }
        Jdbc.close(statement, null);
    }


}
